package wwiii;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;

public class PlayerManager {
	@SuppressWarnings("unchecked")
	public void clearPlayers() {
		final PersistenceManager pm = PMF.getPM();

		try {
			final Query query = pm.newQuery(Player.class);
			final List<Player> players = (List<Player>) query.execute();

			pm.deletePersistentAll(players);
		} finally {
			pm.close();
		}
	}

	public void storePlayer(Player player) {
		final PersistenceManager pm = PMF.getPM();

		try {
			pm.makePersistent(player);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public Player loadPlayer(String id) {
		final PersistenceManager pm = PMF.getPM();

		try {
			final Query query = pm.newQuery(Player.class);
			query.setFilter("key == keyParam");
			query.declareParameters(Key.class.getName() +" keyParam");

			final List<Player> players = (List<Player>) query.execute(Player.getKey(id));

			if (players.isEmpty()) {
				throw new IllegalArgumentException("PlayerID '"+ id +"' is unknown");
			}
			if (players.size() > 1) {
				throw new IllegalArgumentException("PlayerID '"+ id +"' is ambigious");
			}

			return players.get(0);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public Collection<Player> loadPlayers() {
		final PersistenceManager pm = PMF.getPM();

		try {
			final Query query = pm.newQuery(Player.class);

			final List<Player> players = (List<Player>) query.execute();

			return new ArrayList<Player>(players);
		} finally {
			pm.close();
		}
	}
}
